/*
 * This file is part of the SDWebImage package.
 * (c) Olivier Poitrey <rs@dailymotion.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#import "UIImageView+WebCache.h"
#import "UIView+Ext.h"
#import "SDImageCache.h"

@interface UIImageView ()

@property (nonatomic, copy) NSString* imageurl;                             // 图片url
@property (nonatomic, assign) BOOL isFileExist;                             // 判断图片文件是否存在
@property (nonatomic, assign) BOOL isAnimation;                             // 是否显示动画
@property (nonatomic, assign) BOOL zoomStatus;
@end

static char kUrlImageViewKey;
static char kPlaceholderImageViewKey;
static char kImageUrlKey;
static char kIsFileExistKey;
static char kIsAnimationKey;
static char kzoomStatusKey;
@implementation UIImageView (WebCache)

-(BOOL )isFileExist
{
    BOOL ret = [((NSString* )objc_getAssociatedObject(self, &kIsFileExistKey)) intValue];
    return ret;
}

-(void)setIsFileExist:(BOOL )isExist
{
    objc_setAssociatedObject(self, &kIsFileExistKey, [NSString stringWithFormat:@"%d", isExist], OBJC_ASSOCIATION_COPY);
}

-(BOOL )isAnimation
{
    NSString* ani = ((NSString* )objc_getAssociatedObject(self, &kIsAnimationKey));
    return ani ? [ani intValue] : YES;
}

-(void)setIsAnimation:(BOOL )isAnimation
{
    objc_setAssociatedObject(self, &kIsAnimationKey, [NSString stringWithFormat:@"%d", isAnimation], OBJC_ASSOCIATION_COPY);
}

- (BOOL)zoomStatus
{
    NSString* ani = ((NSString* )objc_getAssociatedObject(self, &kzoomStatusKey));
    return ani ? [ani intValue] : YES;
}

- (void)setZoomStatus:(BOOL)zoomStatus
{
   objc_setAssociatedObject(self, &kzoomStatusKey, [NSString stringWithFormat:@"%d", zoomStatus], OBJC_ASSOCIATION_COPY);
}

-(NSString* )imageurl
{
    return objc_getAssociatedObject(self, &kImageUrlKey);
}

-(void)setImageurl:(NSString* )imageurlString
{
    objc_setAssociatedObject(self, &kImageUrlKey, imageurlString, OBJC_ASSOCIATION_COPY);
}


-(UIImageView* )urlImageView
{
    return (UIImageView* )objc_getAssociatedObject(self, &kUrlImageViewKey);
}

-(void)setUrlImageView:(UIImageView *)urlImageView
{
    objc_setAssociatedObject(self, &kUrlImageViewKey, urlImageView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIImageView* )placeholderImageView
{
     return (UIImageView* )objc_getAssociatedObject(self, &kPlaceholderImageViewKey);
}

-(void)setPlaceholderImageView:(UIImageView *)placeholderImageView
{
       objc_setAssociatedObject(self, &kPlaceholderImageViewKey, placeholderImageView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)createWebCacheSubViews
{
    if (self.placeholderImageView == nil) {
        UIImageView* placeholder = [((UIImageView* )[UIImageView alloc]) initWithFrame:self.bounds];
        placeholder.clipsToBounds = self.clipsToBounds;
        placeholder.contentMode = self.contentMode;
        self.placeholderImageView = placeholder;
        [self addSubview:self.placeholderImageView];
        [placeholder release];
    }

    if (self.urlImageView == nil) {
        UIImageView* urlImage = [((UIImageView* )[UIImageView alloc]) initWithFrame:self.bounds];
        urlImage.clipsToBounds = self.clipsToBounds;
        urlImage.contentMode = self.contentMode;
        self.urlImageView = urlImage;
        [self addSubview:self.urlImageView];
        [urlImage release];
    }

//    self.isAnimation = YES;
}

//add by xuanwenchao 2012.12.18
- (void)setImageWithURLString:(NSString *)urlStr
{
    if(urlStr == nil || [urlStr isKindOfClass:[NSNull class]]){
        return;
    }
    
    NSURL *url = [NSURL URLWithString:urlStr];
    [self setImageWithURL:url];
}

- (void)setImageWithURLString:(NSString *)urlStr placeholderImage:(UIImage *)placeholder
{
    if(urlStr == nil || [urlStr isKindOfClass:[NSNull class]]){
        return;
    }
    
    NSURL *url = [NSURL URLWithString:urlStr];
    [self setImageWithURL:url placeholderImage:placeholder];
}

- (void)setImageWithURL:(NSURL *)url
{
    [self setImageWithURL:url placeholderImage:nil];
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder
{
    [self setImageWithURL:url placeholderImage:placeholder options:0];
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder zoom:(BOOL)zoomStatus
{
    [self setImageWithURL:url placeholderImage:placeholder zoom:zoomStatus options:0];
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options
{
    self.imageurl = [url absoluteString];
    self.isFileExist = ([[NSFileManager defaultManager] fileExistsAtPath:[[SDImageCache sharedImageCache] cachePathForKey:self.imageurl]]
                        || [[SDImageCache sharedImageCache] isExistInMemoryFromKey:[[SDImageCache sharedImageCache] cachePathForKey:self.imageurl]]);

    SDWebImageManager *manager = [SDWebImageManager sharedManager];

    // Remove in progress downloader from queue
    [manager cancelForDelegate:self];
    
//    self.image = placeholder;
    [self createWebCacheSubViews];
    self.placeholderImageView.image = placeholder;
    self.placeholderImageView.hidden = NO;
    self.placeholderImageView.alpha = 1.0f;
    self.urlImageView.alpha = 0.0f;

    if (url)
    {
        [manager downloadWithURL:url delegate:self options:options];
    }
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder zoom:(BOOL)zoomStatus options:(SDWebImageOptions)options
{
    self.zoomStatus = zoomStatus;
    self.imageurl = [url absoluteString];
    self.isFileExist = ([[NSFileManager defaultManager] fileExistsAtPath:[[SDImageCache sharedImageCache] cachePathForKey:self.imageurl]]
                        || [[SDImageCache sharedImageCache] isExistInMemoryFromKey:[[SDImageCache sharedImageCache] cachePathForKey:self.imageurl]]);
    
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
    // Remove in progress downloader from queue
    [manager cancelForDelegate:self];
    
    //    self.image = placeholder;
    [self createWebCacheSubViews];
    self.placeholderImageView.image = placeholder;
    self.placeholderImageView.hidden = NO;
    self.placeholderImageView.alpha = 1.0f;
    self.urlImageView.alpha = 0.0f;
    
    if (url)
    {
        [manager downloadWithURL:url delegate:self options:options];
    }
}

#if NS_BLOCKS_AVAILABLE
- (void)setImageWithURL:(NSURL *)url success:(SDWebImageSuccessBlock)success failure:(SDWebImageFailureBlock)failure;
{
    [self setImageWithURL:url placeholderImage:nil success:success failure:failure];
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder success:(SDWebImageSuccessBlock)success failure:(SDWebImageFailureBlock)failure;
{
    [self setImageWithURL:url placeholderImage:placeholder options:0 success:success failure:failure];
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options success:(SDWebImageSuccessBlock)success failure:(SDWebImageFailureBlock)failure;
{
    self.imageurl = [url absoluteString];
    self.isFileExist = ([[NSFileManager defaultManager] fileExistsAtPath:[[SDImageCache sharedImageCache] cachePathForKey:self.imageurl]]
                        || [[SDImageCache sharedImageCache] isExistInMemoryFromKey:[[SDImageCache sharedImageCache] cachePathForKey:self.imageurl]]);

    SDWebImageManager *manager = [SDWebImageManager sharedManager];

    // Remove in progress downloader from queue
    [manager cancelForDelegate:self];

//    self.image = placeholder;
    [self createWebCacheSubViews];
    self.placeholderImageView.image = placeholder;
    self.placeholderImageView.hidden = NO;
    self.placeholderImageView.alpha = 1.0f;
    self.urlImageView.alpha = 0.0f;

//    if (self.isFileExist) {
//        self.placeholderImageView.hidden = YES;
//        self.urlImageView.alpha = 1.0f;
//    }else {
//        self.placeholderImageView.hidden = NO;
//        self.placeholderImageView.alpha = 1.0f;
//        self.urlImageView.alpha = 0.0f;
//    }
    
    if (url)
    {
        [manager downloadWithURL:url delegate:self options:options success:success failure:failure];
    }
}
#endif

- (void)cancelCurrentImageLoad
{
    [[SDWebImageManager sharedManager] cancelForDelegate:self];
}

- (void)webImageManager:(SDWebImageManager *)imageManager didProgressWithPartialImage:(UIImage *)image forURL:(NSURL *)url
{
    self.image = image;
    [self setNeedsLayout];
}

- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image forURL:(NSURL *)url;
{
//    self.image = image;
    
    if ([self.imageurl isEqualToString:[url absoluteString]]) {
        
        if (self.zoomStatus) {
             self.urlImageView.image = [image imageCompressForWidth:self.frameWidth];
        }else{
             self.urlImageView.image = image;
        }
        self.urlImageView.alpha = 1.0f;
    }
    
    if (self.isAnimation && !self.isFileExist) {
        CAAnimation *theAnimation2 = [self animationWithOpacityFrom:1.0 To:0.0 Duration:1.1 BeginTime:0];
        [self.placeholderImageView.layer addAnimation:theAnimation2 forKey:nil];
        
        CAAnimation *theAnimation = [self animationWithOpacityFrom:0.0 To:1.0 Duration:1.1 BeginTime:0];
        [self.urlImageView.layer addAnimation:theAnimation forKey:nil];
    }else {
        self.placeholderImageView.hidden = YES;
    }

//    [self setNeedsLayout];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    self.placeholderImageView.hidden = YES;
}

- (void)layoutSubviews
{
    self.urlImageView.frame = self.bounds;
    self.placeholderImageView.frame = self.bounds;
}

@end
